import os
import wave
import numpy as np
import librosa
import librosa.display
import matplotlib.pyplot as plt

def split_audio(input_file, output_dir):
    
    # 打开音频文件
    with wave.open("audio_train/run162/audio/"+input_file+"-50s.wav", 'rb') as audio_file:
        # 获取音频文件的参数
        params = audio_file.getparams()
        # 获取音频文件的采样率
        sample_rate = params.framerate
        # 获取音频文件的帧数
        num_frames = params.nframes
        # 计算每秒的帧数
        frames_per_second = sample_rate
        
        # 切分音频文件
        for i in range(0, num_frames, frames_per_second):
            # 设置切分后的音频文件名
            # 如果目录不存在则创建目录
            os.makedirs(output_dir, exist_ok=True)
            second = i // frames_per_second
            output_file = os.path.join(output_dir, f'run162-A1P07-{second}.wav'.format(i))
            # 创建新的音频文件
            with wave.open(output_file, 'wb') as output_audio:
                # 设置新音频文件的参数
                output_audio.setparams(params)
                # 从原始音频文件中读取帧数据
                audio_data = audio_file.readframes(frames_per_second)
                # 将帧数据写入新的音频文件
                output_audio.writeframes(audio_data)
        print('切割完成')
def specshow(file_path):
    y, sr = librosa.load(file_path)

    # 计算频谱
    D = librosa.amplitude_to_db(librosa.stft(y), ref=np.max)

    # 绘制频谱图
    plt.figure(figsize=(14, 5))
    librosa.display.specshow(D, sr=sr, x_axis='time', y_axis='log')
    plt.colorbar(format='%+2.0f dB')
    plt.title('Spectrogram')
    plt.show()


if __name__ == '__main__':
    # input_file = 'run162-A1P03'
    # output_dir = 'split/run162-A1P07-02'
    # split_audio(input_file, output_dir)
    filepath = 'data/audio/run162-A1P07.wav'
    specshow(filepath)
    
    